package uf.audit.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;
import org.apache.log4j.Logger;

/**
 * MD5支持类，在密码加密等场合需要用到
 * 
 * @author sunny
 *
 */
public class MD5 {
	private static final Logger log = Logger.getLogger(MD5.class);
	protected static MessageDigest messagedigest = null;
	protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	static {
		try {
			messagedigest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage());
		}
	}

	public static String getFileMD5String(File file) throws IOException {
		FileInputStream in = new FileInputStream(file);
		String result = getFileMD5String(in);
		in.close();
		return result;
	}

	public static String getStringMD5String(String str) {
		StringBuffer sb = new StringBuffer(32);
		try {
			byte[] array = messagedigest.digest(str.getBytes("UTF-8"));
			for (int i = 0; i < array.length; i++) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
						.toUpperCase().substring(1, 3));
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return null;
		}
		return sb.toString();
	}

	public static String getFileMD5String(InputStream in) throws IOException {
		byte[] buffer = new byte[102400];
		int length;
		while ((length = in.read(buffer)) != -1) {
			messagedigest.update(buffer, 0, length);
		}
		return new String(Hex.encodeHex(messagedigest.digest()));
	}
	
	public static void main(String[] args) {
		System.out.println(MD5.getStringMD5String("admin"));
	}
}
